package com.ruoyi.find.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.find.domain.LoginDriver;
import com.ruoyi.find.mapper.LoginDriverMapper;
import com.ruoyi.find.service.LoginDriverService;
import com.ruoyi.find.untils.MobileMessageUtil;

import com.ruoyi.find.vo.LoginVo;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author HP
* @description 针对表【login_driver(网约车司机信息表（含登录功能）)】的数据库操作Service实现
* @createDate 2025-08-27 14:43:06
*/
@Service
public class LoginDriverServiceImpl extends ServiceImpl<LoginDriverMapper, LoginDriver>
    implements LoginDriverService {
    @Autowired
    private LoginDriverMapper loginDriverMapper;
    private static final Logger log = LoggerFactory.getLogger(LoginDriverServiceImpl.class);
    private HashMap<String, String> codeMap = new HashMap<>();
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    TokenService tokenService;


    @Override
    public AjaxResult sendCode(String mobile) {
        //生成四位随机数
        String code = String.valueOf(RandomUtils.nextInt(1000, 9999));
        LambdaQueryWrapper<LoginDriver> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoginDriver::getPhone, mobile);
        LoginDriver loginDriver = loginDriverMapper.selectOne(wrapper);
        if(loginDriver==null){
            return AjaxResult.error("此手机号码未添加为司机");
        }
        log.info("发送验证码:{}", code);
        redisTemplate.opsForValue().set(mobile, code,60, TimeUnit.SECONDS);
        MobileMessageUtil.sendMobileMessage(mobile, code);
        return AjaxResult.success("验证码发送成功:"+code);
    }

    @Override
    public AjaxResult phoneLogin(LoginVo loginVo) {
        String mobile = loginVo.getPhone();
        String code = loginVo.getPhoneCode();
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if(redisCode==null){
            return AjaxResult.error("验证码已过期");
        }
        if(!redisCode.equals(code)){
            return AjaxResult.error("验证码不存在");
        }
        LambdaQueryWrapper<LoginDriver> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoginDriver::getPhone, mobile);
        LoginDriver loginDriver = loginDriverMapper.selectOne(wrapper);
        if(loginDriver==null) {
            return AjaxResult.error("手机号不存在");
        }
        Map<String, Object> driverMap = new HashMap<>();
        driverMap.put("driver", loginDriver);
        String token = JwtUtils.createToken(driverMap);
        loginDriver.setToken(token);
        return AjaxResult.success(loginDriver);
    }

    @Override
    public AjaxResult getDriverInfo(String token) {
        // 1. 使用若依工具类解析JWT获取Claims
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            throw new RuntimeException("无效的JWT令牌");
        }

        // 2. 从Claims中获取存储的driver信息（此时是LinkedHashMap类型）
        Object driverObj = claims.get("driver"); // 假设存储时的key是"driver"

        // 3. 转换为LoginDriver对象（核心修复步骤）
        if (driverObj == null) {
            throw new RuntimeException("JWT中未包含司机信息");
        }
        LoginDriver loginDriver = new ObjectMapper().convertValue(driverObj, LoginDriver.class);
        return AjaxResult.success(loginDriver);
    }




}




